#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <vector>
#include "Mutex.hpp"

using namespace std;

#define NUM 4

int tickets = 1000;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;

class ThreadData
{
public:
    pthread_t tid;
    string name_;
};

void *GetTickets(void *arg)
{
    while (1)
    {
        //pthread_mutex_lock(&mutex);   //加锁
        Mutex mutex_(&mutex);
        ThreadData* thread=static_cast<ThreadData *>(arg);
        if (tickets > 0)
        {
            usleep(1000);
            cout <<thread->name_<< " 正在抢票：" << tickets-- << endl;
            //pthread_mutex_unlock(&mutex);  //解锁
        }
        else
        {
            //pthread_mutex_unlock(&mutex);  //解锁
            break;        //没有票则退出
        }
        //pthread_mutex_unlock(&mutex)  //若在此处解锁当则会造成死锁
    }
    //usleep(1000);
    return nullptr;
}
int main()
{
    pthread_mutex_init(&mutex,nullptr);
    vector<ThreadData *> threads;
    for (int i = 0; i < NUM; i++)
    {
        ThreadData *thread = new ThreadData();
        string name="thread "+to_string(i);
        thread->name_=name;
        threads.push_back(thread);
        pthread_create(&thread->tid, nullptr, GetTickets, (void *)thread);
    }
    for (auto &it : threads)
    {
        pthread_join(it->tid, nullptr);
    }
    pthread_mutex_destroy(&mutex);
}